package fun.flyee.android.pengshan.acts;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.huawei.hms.hmsscankit.RemoteView;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import fun.flyee.android.pengshan.Constant;
import fun.flyee.pengshan.social.R;
import fun.flyee.android.pengshan.utils.Systems;
import fun.flyee.android.pengshan.utils.Util;
import fun.flyee.android.pengshan.widgets.Tips;

public class QRCodeActivity extends BaseActivity {

    @BindView(R.id.camera_container)
    public FrameLayout cameraContainer;
    @BindView(R.id.line_view)
    public View lineView;

    private RemoteView cameraView;
    private int animaBegin, animaDistance;
    private AnimatorSet animatorSet;

    @Override
    public void onCreate(Bundle b) {
        super.onCreate(b);
        int mScreenWidth = Systems.getScreenWidth(this);
        int mScreenHeight = Systems.getScreenHeight(this);
        animaDistance = mScreenWidth;
        animaBegin = mScreenHeight / 2 - animaDistance / 2 - Util.dp2px(this, 90);
        // 当前Demo扫码框的宽高是300dp。
        final int SCAN_FRAME_SIZE = 300;
        int scanFrameSize = (int) (SCAN_FRAME_SIZE * getResources().getDisplayMetrics().density);
        Rect rect = new Rect();
        rect.left = mScreenWidth / 2 - scanFrameSize / 2;
        rect.right = mScreenWidth / 2 + scanFrameSize / 2;
        rect.top = mScreenHeight / 2 - scanFrameSize / 2;
        rect.bottom = mScreenHeight / 2 + scanFrameSize / 2;
        cameraView = new RemoteView.Builder()
                .setContext(this)
                .setBoundingBox(rect)//设置扫描区域
                .setContinuouslyScan(false)//设置识别码制式
                .setFormat(HmsScan.QRCODE_SCAN_TYPE, HmsScan.DATAMATRIX_SCAN_TYPE)
                .build();
        // 将自定义view加载到activity的frameLayout中。
        cameraView.onCreate(b);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        cameraContainer.addView(cameraView, params);
        cameraView.setOnResultCallback((HmsScan[] results) -> returnResult(results));
    }

    @Override
    public void onPostCreate(Bundle b) {
        super.onPostCreate(b);
        ((LinearLayout.LayoutParams) (lineView.getLayoutParams())).topMargin = animaBegin;
        setupAnimator();
    }

    private void setupAnimator() {
        ObjectAnimator yAnimator = ObjectAnimator.ofFloat(lineView, "translationY", animaBegin, animaDistance);
        yAnimator.setDuration(4500);
        ObjectAnimator aAnimator1 = ObjectAnimator.ofFloat(lineView, "alpha", 0f, 1f);
        aAnimator1.setDuration(500);
        ObjectAnimator aAnimator2 = ObjectAnimator.ofFloat(lineView, "alpha", 1f, 1f);
        aAnimator2.setDuration(3500);
        ObjectAnimator aAnimator3 = ObjectAnimator.ofFloat(lineView, "alpha", 1f, 0f);
        aAnimator3.setDuration(500);
        AnimatorSet aSet = new AnimatorSet();
        aSet.playSequentially(aAnimator1, aAnimator2, aAnimator3);
        animatorSet = new AnimatorSet();
        animatorSet.playTogether(yAnimator, aSet);
        Animator.AnimatorListener listener = new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (animatorSet != null && animatorSet.isRunning()) {
                    animatorSet.start();
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        };
        animatorSet.addListener(listener);
        animatorSet.start();
    }

    @Override
    protected int layoutId() {
        return R.layout.act_qrcode;
    }

    @OnClick(R.id.back_btn)
    public void onBack() {
        this.finish();
    }

    @OnClick(R.id.img_btn)
    public void onAlbumn() {
        Router.photo(this, 1);
//        Router.sysPhoto(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.INTENT_REQUEST_PHOTO_CHOOSE && resultCode == RESULT_OK) {
            List<String> photoPaths = BGAPhotoPickerActivity.getSelectedPhotos(data);
            if (photoPaths == null || photoPaths.size() == 0) {
                return;
            }
//            scanView.toParse(photoPaths.get(0));
            try {
                InputStream input = new FileInputStream(photoPaths.get(0));
                Bitmap bitmap = BitmapFactory.decodeStream(input);
                input.close();
                HmsScan[] hmsScans = ScanUtil.decodeWithBitmap(this, bitmap, new HmsScanAnalyzerOptions.Creator().setPhotoMode(true).create());
                returnResult(hmsScans);
            } catch (IOException e) {
                Tips.toast("文件未找到");
            }
        }
    }

    private void returnResult(HmsScan[] results) {
        if (results != null && results.length > 0 && results[0] != null) {
            String text = results[0].getOriginalValue().replaceAll("\r", "").replaceAll("\n", "|");
            if (!TextUtils.isEmpty(text)) {
                Intent data = new Intent();
                data.putExtra("data", text);
                setResult(RESULT_OK, data);
                finish();
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (cameraView != null) cameraView.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (cameraView != null) cameraView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (cameraView != null) cameraView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (cameraView != null) cameraView.onStop();
    }

    @Override
    public void onDestroy() {
        if (cameraView != null) cameraView.onDestroy();
        if (animatorSet != null) {
            animatorSet.cancel();
            animatorSet = null;
        }
        super.onDestroy();
    }

}
